/*
 * Copyright 2007-2009 Thomas Krause (thomas@berlin-reloaded.de)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gidoo.cms.helper;

import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import org.apache.wicket.util.crypt.Base64UrlSafe;
import org.gidoo.cms.GidooCMS;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.filter.ElementFilter;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/**
 * Somer helper Tools.
 * @author <a href="mailto:thomas@berlin-reloaded.de">Thomas Krause</a>
 */
public class Tools
{

  /** The standard gidooCMS DateFormat (yyyy-MM-dd HH:mm) */
  public static final SimpleDateFormat standardDateFormatter =
    new SimpleDateFormat("yyyy-MM-dd HH:mm");

  /**
   * Will do some cleanup on the path <br>
   * More concrete it will remove leading and trailing slashes 
   * e.g. "abc/def/ghi" is clean but "/abc/" is not)
   * @param path The original path
   * @return The "new" path
   */
  public static String cleanupFolderPath(String path)
  {
    String newPath = path;
    if(newPath.startsWith("/"))
    {
      newPath = newPath.substring(1);
    }

    if(newPath.endsWith("/"))
    {
      newPath = newPath.substring(0, path.length() - 1);
    }

    return newPath;
  }

  /**
   * This function will encode a path so it can be used as a name for a node
   * in the drafts.
   * 
   * @param s The input path.
   * @return The encoded name.
   */
  public static String path2DraftName(String s)
  {
    return new String(Base64UrlSafe.encodeBase64(s.getBytes()));
  }

  /**
   * This function will decode a name for a node in the drafts so it can be 
   * used as a path.
   * 
   * @param s The input draft node name.
   * @return The decoded path.
   */
  public static String draftName2Path(String s)
  {
    return new String(Base64UrlSafe.decodeBase64(s.getBytes()));
  }

  /**
   * Get the root URL of the web-application.
   * @param app The application
   * @return The URL in the form "<contextPath>/[<cmspath>/]"
   */
  public static String getRootURLForWebapp(GidooCMS app)
  {
    String result =
      app.getServletContext().getContextPath() +
      "/" + app.CMS_CONFIGURATION.getCMSPath();

    if(!"".equals(app.CMS_CONFIGURATION.getCMSPath()))
    {
      result = result + "/";
    }
    return result;
  }

  /**
   * Returns a string representation where all href-Attributes in images are
   * absolute URLs.<br><br>
   *
   * Please note that this implementation uses JDOM to parse the xhtml.
   * So please be sure to use at least wellformed XHTML. If the document
   * is not wellformed nothing will be replaced (and you will not even get an
   * error).
   *
   * @param app The gidooCMS application
   * @param pathToPage The path to the page (absolute from context).
   * @param xhtml The original XHTML
   * @return
   */
  public static String absolutizeImageTagHrefs(GidooCMS app, String pathToPage, String xhtml)
  {
    String result = xhtml;
    try
    {
      // parse result (should be XHTML)
      Document docResult = new SAXBuilder(false).build(new StringReader(xhtml));
      

      // convert relative image references to absolute ones
      Iterator<Element> itImages = docResult.getDescendants(new ElementFilter("img"));
      while(itImages.hasNext())
      {
        Element e = itImages.next();
        String imgAtt = e.getAttributeValue("src");
        if(imgAtt != null && !(imgAtt.startsWith("http://") || imgAtt.startsWith("https://") || imgAtt.startsWith("/")))
        {
          String newImgAtt = Tools.getRootURLForWebapp(app) + pathToPage + "/" + imgAtt;
          while(newImgAtt.startsWith("//")) 
          { 
            newImgAtt = newImgAtt.substring(1); 
          } 
          e.setAttribute("src", newImgAtt);
        }
      }

      XMLOutputter outputter = new XMLOutputter();
      Format fmt = Format.getPrettyFormat();
      fmt.setOmitDeclaration(true);
      fmt.setOmitEncoding(true);
      outputter.setFormat(fmt);
      
      result = outputter.outputString(docResult);

    }
    catch(Exception ex)
    {
      // ignore
    }
    return result;
  }
}
